package cn.bytecollege.admin.controller;

import cn.bytecollege.admin.service.AdminService;
import cn.bytecollege.common.constant.Resource;
import cn.bytecollege.common.entity.Admin;
import cn.bytecollege.common.util.MD5Util;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "AdminLoginController", value = "/admin/adminLogin")
public class AdminLoginController extends HttpServlet {
    private AdminService adminService = null;

    public AdminLoginController() {
        adminService = new AdminService();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher(Resource.PAGE_LOCATION + "/admin/login.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Admin admin = adminService.findAdminByAdminId(username);
        String msg = null;
        //判断账号是否正确
        if (admin == null) {
            msg = "账号不正确";
            request.setAttribute("msg", msg);
            request.getRequestDispatcher(Resource.PAGE_LOCATION + "/admin/login.jsp").forward(request, response);
            return;
        }
        //执行到这里说明账号正确，判断密码
        if (!MD5Util.md5Encode(password).equals(admin.getAdminPassword())) {
            msg = "密码不正确";
            request.setAttribute("msg", msg);
            request.getRequestDispatcher(Resource.PAGE_LOCATION + "/admin/login.jsp").forward(request, response);
            return;
        }
        //执行到这里说明密码正确
        HttpSession session = request.getSession();
        session.setAttribute("admin", admin);
        request.getRequestDispatcher(Resource.PAGE_LOCATION + "/admin/index.jsp").forward(request, response);
    }
}
